package com.process.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.process.controller.util.Code;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @ClassName: LoginCheckFilter
 * @Author: 殷凡卓
 * @Date: 2023/4/14 22:53
 */

//拦截所有请求
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Order(1)
@Slf4j
public class ALoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Map<String, String> map = new HashMap<>();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers",
                "x-requested-with,Cache-Control,Pragma,Content-Type,token");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
//        String method = request.getMethod();
//        if (method.equalsIgnoreCase("OPTIONS")) {
//            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
//        } else {
//            filterChain.doFilter(servletRequest, servletResponse);
//        }



        //1.1获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html

        log.info("token拦截：{}", requestURI);
        log.info("token是否生效：");

        //1.2定义不需要处理的请求路径
        String[] urls = new String[]{
                "/login",
                "/company/import_teacher",
//                "/excel/importClass",
//                "/excel/importAccount",
//                "/excel/importPracticalTask",
//                "/excel/import_PracticeCourse",
//                "/excel/importTrainPlan",
//                "/excel/import_Teacher",
//                "/excel/import_Student",
                "/students/upload/**",
                "/excel/**",
                "/upload-image",
                "/upload",
                "/preview/**"
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if (check) {
            log.info("Login{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //4、判断token是否正确
        String token = ((HttpServletRequest) servletRequest).getHeader("token");
        if (StringUtils.isNotBlank(token)) {
            //token验证结果
            int verify = jwtUtils.verify(token,request);
            //验证失败
            if (verify != 1) {
                if (verify == 2) {
                    map.put("code", Code.TOKEN_ERR.toString());
                    map.put("msg", "tocken超时");

                } else if (verify == 0) {
                    map.put("code", Code.TOKEN_ERR.toString());
                    map.put("msg", "tocken错误");

                }
            }
            else if (verify == 1) {
                //验证成功，放行
                log.warn("Token成功{}放行",requestURI);
//                获取token中的身份判定和username
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        } else {
            //token为空的返回
            log.warn("Token失败_拦截");

            map.put("code", Code.TOKEN_ERR.toString());
            map.put("msg", "未携带token信息");
        }
        JSONObject jsonObject = new JSONObject(map);
        servletResponse.setContentType("application/json");
        //设置响应的编码
        servletResponse.setCharacterEncoding("utf-8");
        //响应
        PrintWriter pw = servletResponse.getWriter();
        pw.write(jsonObject.toString());
        pw.flush();
        pw.close();

    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
